
package com.tsystems.school.jabber;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;

public class Message {
  public static Message LoadFromJSON(String json){
    return new Message(json);
  }
  
  private HashMap<String, String> content;
  private MessageType             type;
  
  public Message() {
    content = new HashMap<String, String>();
  }
  
  public Message(String json){
    this();
    this.fromJSON(json);
  }
  
  public HashMap<String, String> getContent() {
    return content;
  }
  
  public void setContent(HashMap<String, String> content) {
    this.content = content;
  }
  
  public void putProperty(String key, String value) {
    this.content.put(key, value);
  }
  
  public String getPropertyValue(String key) {
    return this.content.get(key);
  }
  
  public String removeProperty(String key) {
    return this.content.remove(key);
  }
  
  public String toJSON() {
    JsonObject jo = new JsonObject();
    jo.addProperty("type", this.type.toString());
    JsonArray ja = new JsonArray();
    JsonObject j;
    Iterator<Entry<String, String>> i = this.content.entrySet().iterator();
    while (i.hasNext()) {
      Map.Entry me = i.next();
      j = new JsonObject();
      j.add((String) me.getKey(), new JsonPrimitive((String) me.getValue()));
      ja.add(j);
    }
    jo.add("content", ja);
    return jo.toString();
  }
  
  public void fromJSON(String json) {
    JsonObject jo = new JsonObject();
    JsonParser jp = new JsonParser();
    JsonElement je = jp.parse(json);
    if (je.isJsonObject()) {
      jo = je.getAsJsonObject();
      this.type = MessageType.valueOf(jo.get("type").getAsString());
      JsonArray ja = jo.get("content").getAsJsonArray();
      for (int i = 0; i < ja.size(); i++) {
        jo = (ja.get(i)).getAsJsonObject();
        Iterator j = jo.entrySet().iterator();
        while (j.hasNext()) {
          Map.Entry me = (Map.Entry) (j.next());
          this.content.put((String) me.getKey(), ((JsonElement) me.getValue()).getAsString());
        }
      }
    }
  }
  
  public MessageType getType() {
    return type;
  }
  
  public void setType(MessageType type) {
    this.type = type;
  }
}
